#!/usr/bin/python
# -*- coding: utf-8 -*-
import configparser
from enum import Enum
import os, sys
import traceback

from infrastructure.utils.file_util import copy


class ValueTypeEnum(Enum):
    STRING = 'str'
    NONE = 'str'
    INT = 'int'
    BOOL = 'bool'


class Config:
    def __init__(self):
        version = "dev"
        # base_path = os.path.dirname(os.path.abspath(__file__))
        # 解决pyinstaller打包python程序可执行文件路径问题
        if getattr(sys, 'frozen', False):  # 判断是exe还是.py程序
            base_path = os.path.dirname(sys.executable)  # exe程序路径
        elif __file__:
            base_path = os.path.dirname(__file__)  # .py程序路径
        try:
            self.con_base = configparser.ConfigParser()
            self.con_base.read(base_path + os.sep + "config.ini", encoding='utf-8')
            version = self.con_base.get('base', 'version')
        except:
            pass
        yaml_path = "config.{}.ini"
        yaml_path = yaml_path.format(version) if os.path.exists(yaml_path.format(version)) else yaml_path.format('user')
        # 创建配置文件对象
        self.con = configparser.ConfigParser()
        # 读取文件
        self.default_config_path = base_path + os.sep + yaml_path
        self.home_path = os.path.expanduser('~') + os.sep + "lifengNote"
        copy(self.default_config_path, self.home_path) # 复制默认配置文件到本地家目录中
        self.config_path = os.path.join(self.home_path, yaml_path)
        self.con.read(self.config_path, encoding='utf-8')

    def get(self, section: str, key: str, value_type=ValueTypeEnum.STRING):
        try:
            value_type = value_type if isinstance(value_type, ValueTypeEnum) else ValueTypeEnum.STRING
            if section and key and self.con.has_section(section):
                result = {
                    'bool': self.con.getboolean,
                    'int': self.con.getint,
                    'str': self.con.get,
                    'None': self.con.get
                }[str(value_type.value)](section, key, raw=True)
                return result if result else None
        except Exception as e:
            traceback.print_exc()
        return None

    def new_or_update(self, section: str, key: str, value):
        try:
            if section is not None and len(section) > 0 and key is not None and len(key) > 0 and value is not None:
                if not self.con.has_section(section):
                    self.con.add_section(section)
                self.con.set(section, key, value)
                # 把更新写入文件
                self.update_file()
            return True
        except Exception as e:
            traceback.print_exc()
        return False

    def new_or_update_batch(self, section, params:dict):
        try:
            if not self.con.has_section(section):
                self.con.add_section(section)
            for key, value in params.items():
                self.con.set(section, key, value)
            self.update_file() # 把更新写入文件
            return True
        except Exception as e:
            traceback.print_exc()
        return False

    def update_file(self):
        """
        把更新写入文件
        :return:
        """
        with open(self.config_path, "w+") as f:
            self.con.write(f)

config = Config()
# print(config.get("graph_match", "audit_platform_base1"))
